﻿using HCQ2_Common;
using HCQ2_Model.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using HCQ2_Model.VR.Params;
using HCQ2_Model;
using System.IO;
using System.Web;

namespace HCQ2UI_Logic.AdminController
{
    /// <summary>
    ///  广告管理
    /// </summary>
    public class SysBoardController: BaseLogic
    {
        //*********************************广告管理*****************************************
        #region 1.0 广告管理首次进入页面 +ActionResult List()
        /// <summary>
        ///  广告管理首次进入页面
        /// </summary>
        /// <returns></returns>
        [HCQ2_Common.Attributes.Element]
        [HCQ2_Common.Attributes.Load]
        [HttpGet]
        public ActionResult List()
        {
            return View();
        }
        #endregion

        #region 1.1 获取广告一栏数据 +ActionResult GetUserData()
        /// <summary>
        ///  获取广告一栏数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InitTable()
        {
            string boardName = RequestHelper.GetDeStrByName("boardName"),//用户名                
                adType = RequestHelper.GetDeStrByName("adType"),//广告类别
                inDate = RequestHelper.GetStrByName("inDate"),//开始起始
                outDate = RequestHelper.GetStrByName("outDate");//开始截止
            int page = RequestHelper.GetIntByName("page"),
               rows = RequestHelper.GetIntByName("rows"),
               adStatus=RequestHelper.GetIntByName("adStatus"),
               platType= RequestHelper.GetIntByName("platType"),
               proType = RequestHelper.GetIntByName("proType");//产品类别     
            BoardQueryParam paran = new BoardQueryParam { keyword = boardName, adStatus = adStatus, proType = proType, adType = adType, platType = platType, inDate = inDate, outDate = outDate, page = page, rows = rows };
            List<VRBoardADModel> list = operateContext.bllSession.T_VRBoardAD.GetInitTable(paran);
            TableModel tModel = new TableModel()
            {
                total = operateContext.bllSession.T_VRBoardAD.GetInitCount(paran),
                rows = list
            };
            return Json(tModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 1.2 添加广告 + ActionResult AddBoard(VRBoardADModel param)
        /// <summary>
        ///  添加广告
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddBoard(VRBoardADModel param)
        {
            if (param.ad_id > 0)
                return EditBoard(param);
            string fileUrl = string.Empty;
            try
            {
                ModelState.Remove("ad_id");
                if(!ModelState.IsValid)
                    return operateContext.RedirectAjax(1, getErrorMessage(ModelState), "", "");
                bool isMark = AddEditFile(out fileUrl);
                if(!isMark)
                    return operateContext.RedirectAjax(1, "广告添加失败~", "", "");
                T_VRBoardAD board = param.toEntry();
                board.ad_url = fileUrl;
                board.create_id = operateContext.Usr.user_id;
                board.create_name = operateContext.Usr.user_name;
                board.create_time = DateTime.Now;
                board.update_id = operateContext.Usr.user_id;
                board.update_name = operateContext.Usr.user_name;
                board.update_time = DateTime.Now;
                board.group_name = param.group_name;
                board.video_url = param.video_url;
                StringBuilder newUrl = new StringBuilder();
                StringBuilder picContent = new StringBuilder();
                #region 重置内容中的图片
                if (!string.IsNullOrEmpty(board.ad_content) && board.ad_content.IndexOf("<img") > -1)
                {
                    #region 文件上传路径
                    string pathServer = "/uploadFile/VRWebChartFile/" + operateContext.Usr.user_guid + "/" + DateTime.Now.ToString("yyyyMMdd") + "/Breviary/";
                    string uploadPath = request.MapPath(request.ApplicationPath + pathServer);
                    if (!Directory.Exists(uploadPath))
                        Directory.CreateDirectory(uploadPath);
                    #endregion
                    string[] temp = { "src=\"data:image" };
                    string[] urls = board.ad_content.Split(temp, StringSplitOptions.RemoveEmptyEntries);
                    #region 循环处理数据
                    foreach (var item in urls)
                    {
                        if (!item.Contains(";base64,"))
                            newUrl.Append(item);
                        else
                        {
                            string picName = Guid.NewGuid().ToString().Replace("-", ""), prefixStr = string.Empty,
                                 newItem = item.Substring(item.IndexOf("\"") + 1);
                            string[] preConetnt = item.Split(',');
                            prefixStr = preConetnt[0].Split(';')[0].Substring(1);
                            //1.0 找出base64数据
                            string base64Str = preConetnt[1].ToString().Split('"')[0];
                            //base64 图片字符串
                            byte[] picByte = Convert.FromBase64String(base64Str);
                            //保存图片，返回路径
                            string tempName = ImageHelper.CreateImageFromBytes(uploadPath, picName, picByte, prefixStr);
                            //更新链接
                            string tempUrl = "http://" + request.Url.Host + ":" + request.Url.Port + request.ApplicationPath + pathServer + tempName;
                            newUrl.Append($" src=\"{tempUrl}\"");
                            newUrl.Append(newItem);
                            picContent.Append("~" + pathServer + tempName + ";");
                        }
                    }
                    #endregion
                    board.ad_content = newUrl.ToString();
                }
                board.pic_content = picContent.ToString();
                #endregion

                if (!string.IsNullOrEmpty(newUrl.ToString()))
                    board.ad_content = newUrl.ToString();
                int mark = operateContext.bllSession.T_VRBoardAD.Add(board);
                if (mark > 0)
                    return operateContext.RedirectAjax(0, "广告添加成功~", "", "");
                return operateContext.RedirectAjax(1, "广告添加失败~", "", "");
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(fileUrl) && System.IO.File.Exists(Server.MapPath(fileUrl)))
                    System.IO.File.Delete(Server.MapPath(fileUrl));
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 1.3 编辑广告 + ActionResult EditBoard(VRBoardADModel param)
        /// <summary>
        ///  编辑广告
        /// </summary>
        /// <param name="param">广告对象</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditBoard(VRBoardADModel param)
        {
            string fileUrl = string.Empty;
            try
            {
                if (!ModelState.IsValid)
                    return operateContext.RedirectAjax(1, getErrorMessage(ModelState), "", "");
                bool isMark = AddEditFile(out fileUrl, param.ad_id, "edit");
                if (!isMark)
                    return operateContext.RedirectAjax(1, "广告编辑失败~", "", "");
                T_VRBoardAD board = param.toEntry();
                board.ad_url = fileUrl;
                board.update_id = operateContext.Usr.user_id;
                board.update_name = operateContext.Usr.user_name;
                board.update_time = DateTime.Now;
                board.group_name = param.group_name;
                board.video_url = param.video_url;
                string[] str = { "ad_order", "pro_type", "ad_type", "ad_title", "start_time", "end_time", "ad_content", "update_id", "update_name", "update_time", "ad_note", "ad_status", "group_name", "video_url", "platType", "store_id" };
                List<string> modifyStr = new List<string>(str);
                if (!string.IsNullOrEmpty(fileUrl))
                    modifyStr.Add("ad_url");
                StringBuilder newUrl = new StringBuilder();
                StringBuilder picContent = new StringBuilder();
                #region 重置内容中的图片
                //2.0 处理内容图片
                if (board.ad_content?.IndexOf("<img") > -1)
                {
                    #region 文件上传路径
                    string pathServer = "/uploadFile/VRWebChartFile/" + operateContext.Usr.user_guid + "/" + DateTime.Now.ToString("yyyyMMdd") + "/Breviary/";
                    string uploadPath = request.MapPath(request.ApplicationPath + pathServer);
                    if (!Directory.Exists(uploadPath))
                        Directory.CreateDirectory(uploadPath);
                    #endregion
                    string[] temp = { "src=\"data:image" };
                    string[] urls = board.ad_content.Split(temp, StringSplitOptions.RemoveEmptyEntries);
                    #region 循环处理数据
                    foreach (var item in urls)
                    {
                        if (!item.Contains(";base64,"))
                            newUrl.Append(item);
                        else
                        {
                            //文件名，扩展名
                            string picName = Guid.NewGuid().ToString().Replace("-", ""), prefixStr = string.Empty,
                                newItem = item.Substring(item.IndexOf("\"") + 1);
                            string[] preConetnt = item.Split(',');
                            prefixStr = preConetnt[0].Split(';')[0].Substring(1);
                            //1.0 找出base64数据
                            string base64Str = preConetnt[1].ToString().Split('"')[0];
                            //base64 图片字符串
                            byte[] picByte = Convert.FromBase64String(base64Str);
                            //保存图片，返回路径
                            string tempName = ImageHelper.CreateImageFromBytes(uploadPath, picName, picByte, prefixStr);
                            //更新链接
                            string tempUrl = "http://" + request.Url.Host + ":" + request.Url.Port + request.ApplicationPath + pathServer + tempName;
                            newUrl.Append($" src=\"{tempUrl}\"");
                            newUrl.Append(newItem);
                            //picContent.Append("~" + pathServer + tempName + ";");
                        }
                    }
                    #endregion

                    #region 重新提取pic_content
                    if (!string.IsNullOrEmpty(newUrl.ToString()))
                    {
                        string[] picStr = { "<img" };
                        string[] picList = newUrl.ToString().Split(picStr, StringSplitOptions.RemoveEmptyEntries);
                        foreach(string newPic in picList)
                        {
                            int startPic, endPic;
                            string tempPic = string.Empty;
                            if (newPic.Contains("src"))
                            {
                                startPic = newPic.IndexOf("src") + 4;
                                endPic = newPic.IndexOf(">") - 1;
                                tempPic = newPic.Substring(startPic, endPic - startPic);
                                string[] _picList = tempPic.Replace("//", "/").Split('/');
                                string tempUrl = string.Empty;
                                if (_picList.Length > 3)
                                {
                                    for (int i = 3; i < _picList.Length; i++)
                                        tempUrl += "/" + _picList[i].Split('"')[0];
                                }
                                picContent.Append("~" + tempUrl + ";");
                            }
                        }
                    }
                    #endregion
                    
                    board.ad_content = newUrl.ToString();
                    modifyStr.Add("ad_content");
                }
                board.pic_content = picContent.ToString();
                modifyStr.Add("pic_content");
                #endregion

                #region 处理原始图片被删除的
                string pic = operateContext.bllSession.T_VRBoardAD.Select(s => s.ad_id == param.ad_id).FirstOrDefault()?.pic_content;
                if (!string.IsNullOrEmpty(pic))
                {
                    //modifyStr.Add("pic_content");
                    string[] strPic = pic.Split(';');
                    foreach(string item in strPic)
                    {
                        if (!board.ad_content.Contains(item.Trim('~')))
                            //不包含，删除数据
                            if (!string.IsNullOrEmpty(item) && System.IO.File.Exists(Server.MapPath(item)))
                                System.IO.File.Delete(Server.MapPath(item));
                    }
                }
                #endregion
                int markCount = operateContext.bllSession.T_VRBoardAD.Modify(board, s => s.ad_id == param.ad_id, modifyStr.ToArray());
                if (markCount > 0)
                    return operateContext.RedirectAjax(0, "编辑广告成功~", "", "");
                 return operateContext.RedirectAjax(1, "编辑广告失败~", "", "");
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(fileUrl) && System.IO.File.Exists(Server.MapPath(fileUrl)))
                    System.IO.File.Delete(Server.MapPath(fileUrl));
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 1.4 删除广告 +ActionResult DelBoardById(int id)
        /// <summary>
        ///  删除广告
        /// </summary>
        /// <param name="id">广告id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DelBoardById()
        {
            try
            {
                string adId = RequestHelper.GetStrByName("adID");
                if(string.IsNullOrEmpty(adId))
                    return operateContext.RedirectAjax(1, "需要删除的广告不存在或者已经删除~", "", "");
                string[] adIds = adId.Split(',');
                for (int i=0;i< adIds.Length;i++)
                {
                    int ad_id = Convert.ToInt32(adIds[i]);
                    T_VRBoardAD board = operateContext.bllSession.T_VRBoardAD.Select(s => s.ad_id == ad_id).FirstOrDefault();
                    if (board == null)
                        return operateContext.RedirectAjax(1, "需要删除的广告不存在或者已经删除~", "", "");
                    //1.0 删除图片附件
                    if (!string.IsNullOrEmpty(board.ad_url) && System.IO.File.Exists(Server.MapPath(board.ad_url)))
                        System.IO.File.Delete(Server.MapPath(board.ad_url));
                    //2.0 删除内容图片
                    DeletePicByContent(ad_id);
                    operateContext.bllSession.T_VRBoardAD.Delete(s => s.ad_id == ad_id);
                }
                return operateContext.RedirectAjax(0, "数据删除成功~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 删除内容中的图片
        private void DeletePicByContent(int ad_id)
        {
            string picContent = operateContext.bllSession.T_VRBoardAD.Select(s => s.ad_id == ad_id).FirstOrDefault()?.pic_content;
            if (string.IsNullOrEmpty(picContent))
                return;
            string[] pic = picContent.Split(';');
            foreach(string url in pic)
            {
                if (!string.IsNullOrEmpty(url) && System.IO.File.Exists(Server.MapPath(url)))
                    System.IO.File.Delete(Server.MapPath(url));
            }
        }
        #endregion

        #region 获取广告数据
        [HttpPost]
        public ActionResult GetBoardById(int id)
        {
            T_VRBoardAD ad = operateContext.bllSession.T_VRBoardAD.Select(s => s.ad_id == id).FirstOrDefault();
            if(ad==null)
                return operateContext.RedirectAjax(1, "数据为空~", "", "");
            return operateContext.RedirectAjax(0, "数据获取成功~", ad.toPOTO(), "");
        }
        #endregion

        #region 处理附件
        /// <summary>
        ///  处理附件
        ///  add：添加，edit：编辑
        /// </summary>
        /// <param name="id"></param>
        /// <param name="fileType"></param>
        /// <returns></returns>
        private bool AddEditFile(out string fileUrl,int id=0,string fileType="add")
        {
            fileUrl = string.Empty;
            try
            {
                T_VRBoardAD ad = null;
                if (id > 0)
                    ad = operateContext.bllSession.T_VRBoardAD.Select(s => s.ad_id == id).FirstOrDefault();
                var files = Request.Files;
                if (files != null && files.Count > 0)
                {
                    #region 1.0 处理附件上传文件夹
                    string pathServer = "/uploadFile/VRBoard/" + operateContext.Usr.user_guid + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                    string uploadPath = request.MapPath(request.ApplicationPath + pathServer);
                    if (!Directory.Exists(uploadPath))
                        Directory.CreateDirectory(uploadPath);
                    #endregion

                    #region 2.0 处理附件
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFileBase file = files[i];
                        if (null == file)
                            continue;
                        if(ad!=null && !string.IsNullOrEmpty(ad.ad_url) && System.IO.File.Exists(Server.MapPath(ad.ad_url)))
                            System.IO.File.Delete(Server.MapPath(ad.ad_url));
                        fileUrl = "~" + pathServer + Helper.GetGuid + "." + file.FileName.Split('.')[1];
                        //1.上传文档
                        file.SaveAs(Server.MapPath(fileUrl));//保存上传文件
                    }
                    #endregion
                }
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        } 
        #endregion
    }
}
